﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Xml.Serialization;

using TeamFoundationServerSensor;

using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudio.TestTools.UnitTesting.Web;

namespace HackystatVSTFSSensorUnitTest {

    /// <summary>
    /// A class used to put general helper methods used in tests.
    /// </summary>
    static class HelperFunctions {

        /// <summary>
        /// The location of the TeamFoundationServer.
        /// </summary>
        private static string server;

        /// <summary>
        /// Attempts to drop the given database.
        /// </summary>
        /// <returns>True if database was droped successfully.</returns>
        public static Boolean dropDatabase(string database) {

            Boolean success = false;

            SqlConnection.ClearAllPools();
            SqlConnection conn = Connections.getNewSQLConnection("master");
            try {
                // Create query to drop for database.
                string query = "IF EXISTS(SELECT NAME FROM master.dbo.sysdatabases WHERE NAME = N'" + database + "') DROP DATABASE " + database;
                SqlCommand command = new SqlCommand(query, conn);

                // Open connection and execute query.
                conn.Open();
                command.ExecuteNonQuery();
                success = true;
            }
            catch (Exception e) {
                Assert.Inconclusive("Precondition: " + e.ToString());
            }
            finally {
                conn.Close();
            }

            return success;
        }

        /// <summary>
        /// Attempts to drop the given table from the database.
        /// </summary>
        /// <returns>True if table was droped successfully.</returns>
        public static Boolean dropTable(string database, string table) {

            Boolean success = false;

            SqlConnection conn = Connections.getNewSQLConnection(database);
            try {

                // Create query to drop for database.
                string query = "IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + table + "') DROP TABLE \"" + table + "\"";
                SqlCommand command = new SqlCommand(query, conn);

                // Open connection and execute query.
                conn.Open();
                command.ExecuteNonQuery();
                success = true;
            }
            catch (Exception e) {
                Assert.Inconclusive("Precondition: " + e.ToString());
            }
            finally {
                conn.Close();
            }

            return success;
        }

        /// <summary>
        /// Returns a string built for testing web services.
        /// </summary>
        /// <param name="url">The test URL of the tfsIdentity.</param>
        /// <returns>String representation of the xml Document</returns>
        public static string gettfsIdentityXml(string url) {
            TFSIdentity tfsXML = new TFSIdentity();
            tfsXML.Url = url;
            return XMLStringSerialize(tfsXML, typeof(TFSIdentity));
        }

        /// <summary>
        /// Serialize a object to xml string.
        /// </summary>
        /// <remarks>
        /// Adapted from: http://www.c-sharpcorner.com/UploadFile/chauhan_sonu57/SerializingObjects07202006065806AM/SerializingObjects.aspx
        /// </remarks>
        /// <param name="instance">The instance of the object to be serialized.</param>
        /// <param name="instanceType">The type of object to be serialized.</param>
        /// <returns>XML string representing the xml document.</returns>
        public static string XMLStringSerialize(object instance, System.Type instanceType) {

            // Declare a basic namespace.
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
            ns.Add("xsd", "http://www.w3.org/2001/XMLSchema");
            ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance");

            // Create a new serializer
            XmlSerializer ser = new XmlSerializer(instanceType);
            MemoryStream memStream = new MemoryStream();
            XmlTextWriter xmlWriter = new XmlTextWriter(memStream, Encoding.Unicode);
            xmlWriter.Namespaces = true;

            // Serialize the class
            ser.Serialize(xmlWriter, instance, ns);
            xmlWriter.Close();
            memStream.Close();

            // Convert the bytes in the buffer to a Unicode string.
            string xml = Encoding.Unicode.GetString(memStream.GetBuffer());
            xml = xml.Substring(xml.IndexOf(Convert.ToChar(60)));
            xml = xml.Substring(0, (xml.LastIndexOf(Convert.ToChar(62)) + 1));
            return xml;
        }

        /// <summary>
        /// Get and Set for server
        /// </summary>
        public static string Server {
            get { return server; }
            set { server = value; }
        }
    }
}
